package com.tanhua.dubbo.server.api.impl;

import com.alibaba.dubbo.config.annotation.Service;

import com.tanhua.dubbo.server.api.RecommendUserApi;

import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(version = "1.0.0")//申明这是一个dubbo服务
public class RecommendUserApiImpl implements RecommendUserApi {
    @Autowired
    private MongoTemplate mongoTemplate;

/*
    @Override
    public RecommendUser queryWithMaxScore(Long toUserId) {
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("toUserId").is(toUserId)),//条件
                Aggregation.group("toUserId").max("score").as("score")//分组字段
        );

        AggregationResults<RecommendUser> outputType = mongoTemplate.aggregate(agg, "recommend_user", RecommendUser.class);
        List<RecommendUser> list = outputType.getMappedResults();
        System.out.println(list);
        return list.get(0);

        */
/*AggregationResults<Integer> outputType = mongoTemplate.aggregate(agg, "recommend_user", Integer.class);
        List<Integer> list = outputType.getMappedResults();
        System.out.println(list);
        return null;*//*

    }
*/


    /**
     * mongoTemplate中查询今日佳人
     * @param toUserId
     * @return
     */
    @Override
    public RecommendUser queryWithMaxScore(Long toUserId) {
        //查询得分最高的用户，按照得分倒序排序
        Query query = Query.query(Criteria.where("toUserId").is(toUserId))
                .with(Sort.by(Sort.Order.desc("score"))).limit(1);
        return this.mongoTemplate.findOne(query, RecommendUser.class);
    }

    /**
     * mongoTemplate中查询推荐列表
     * @param toUserId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<RecommendUser> queryPageInfo(Long toUserId, Integer pageNum, Integer pageSize) {
        //前端传的pageNum是从1开始的;PageRequest.of中的page是从0开始的
        Pageable pageRequest = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Order.desc("score")));
        Query query = Query.query(Criteria.where("toUserId").is(toUserId)).with(pageRequest);
        List<RecommendUser> recommendUsers = this.mongoTemplate.find(query, RecommendUser.class);
        return new PageInfo<>(recommendUsers.size(), pageNum, pageSize, recommendUsers);
    }
}
